package org.springframework.samples.petclinic.validation

import org.springframework.util.StringUtils
import org.springframework.validation.Errors

import org.springframework.samples.petclinic.Owner

class OwnerValidator {

  def validate(owner:Owner, errors:Errors):Unit = {
    if (!StringUtils.hasLength(owner.firstName)) {
      errors.rejectValue("firstName", "required", "required");
    }
    if (!StringUtils.hasLength(owner.lastName)) {
      errors.rejectValue("lastName", "required", "required");
    }
    if (!StringUtils.hasLength(owner.address)) {
      errors.rejectValue("address", "required", "required");
    }
    if (!StringUtils.hasLength(owner.city)) {
      errors.rejectValue("city", "required", "required");
    }
    
    val telephone: String = owner.telephone
    if (!StringUtils.hasLength(telephone)) {
      errors.rejectValue("telephone", "required", "required");
    }
    else {
      for (i <- 0 until telephone.length) {
        if ((Character.isDigit(telephone.charAt(i))) == false) {
          errors.rejectValue("telephone", "nonNumeric", "non-numeric")
          //the java code has a break here but scala does not have a break
          //in this case a return has the same effect 
          return ()
        }
      } 
    }
  }
}
